package cn.b.sky.admin.controller;

import cn.b.sky.admin.constants.SystemConstant;
import cn.b.sky.admin.enums.DwzCallbackType;
import cn.b.sky.admin.enums.DwzStatusCode;
import cn.b.sky.admin.model.BatchJobReport;
import cn.b.sky.admin.model.DWZResult;
import cn.b.sky.admin.model.ECode;
import cn.b.sky.admin.model.ResourceEntity;
import cn.b.sky.admin.model.condition.ResourceCondition;
import cn.b.sky.admin.service.AdminECodeService;
import cn.b.sky.admin.service.AdminResourceService;
import cn.b.sky.admin.utils.ManagementSecurity;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <strong>Title : ResourceController.java<br></strong>
 * <strong>Package : cn.b.sky.admin.controller<br></strong>
 * <strong>Description : </strong>资源管理控制器<br> 
 * <strong>Create on : 2016-6-7 下午2:40:41<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping(value = "/management/resource/*")
public class ResourceController extends BaseController {
  
  @Resource
  private AdminResourceService adminResourceService;

  @Resource
  private AdminECodeService admineCodeService;

  private static final String RESOURCETYPEECODE = "RESOURCETYPEECODE";

  private static final String NAVTABID = "navTabId";

  @RequestMapping("resourceList")
  public String resourceList(Model model, @ModelAttribute("condition") ResourceCondition resource, String navTabId,
                             HttpSession httpSession) {
    resource.setLanguageCode(SystemConstant.LANGUAGE_CODE_ZH);
    resource.seteCodeType(RESOURCETYPEECODE);
    List<ResourceEntity> resources = adminResourceService.selectResourceList(resource);
    int count = adminResourceService.selectResourceCount(resource);
    List<ECode> types = admineCodeService.selectECodeList(RESOURCETYPEECODE, SystemConstant.LANGUAGE_CODE_ZH);
    resource.setData(resources);
    resource.setTotalCount(count);
    model.addAttribute("page", resource);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("resourceType", types);
    return "admin/resource/resource_list";
  }

  @RequestMapping("addResource")
  public String addService(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    List<ECode> types = admineCodeService.selectECodeList(RESOURCETYPEECODE, SystemConstant.LANGUAGE_CODE_ZH);
    model.addAttribute("resourceType", types);
    return "admin/resource/resource_add";
  }

  @RequestMapping("modifyResource")
  public String modifyResource(Model model, String navTabId, String id) {
    ResourceEntity resource = adminResourceService.selectResource(id);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("resource", resource);
    List<ECode> types = admineCodeService.selectECodeList(RESOURCETYPEECODE, SystemConstant.LANGUAGE_CODE_ZH);
    model.addAttribute("resourceType", types);
    return "admin/resource/resource_add";
  }

  @RequestMapping("viewResource")
  public String viewResource(Model model, String navTabId, String id) {
    ResourceEntity resource = adminResourceService.selectResource(id);
    List<ECode> types = admineCodeService.selectECodeList(RESOURCETYPEECODE, SystemConstant.LANGUAGE_CODE_ZH);
    model.addAttribute("resourceType", types);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("resource", resource);
    return "admin/resource/resource_view";
  }

  @RequestMapping("saveResource")
  @ResponseBody
  public DWZResult saveResource(Model model, String navTabId, String id, ResourceEntity resource,
                                HttpServletRequest request) {
    if (resource == null) {
      return ajaxError(SystemConstant.PARAMETERNULL);
    }
    resource.setCreateDateTime(new Date());
    resource.setCreateUser(ManagementSecurity.getCurrentUserCode());
    resource.setModifyDateTime(new Date());
    resource.setModifyUser(ManagementSecurity.getCurrentUserCode());
    if (StringUtils.isEmpty(id)) {
      adminResourceService.insertResource(resource);
    } else {
      adminResourceService.updateResource(resource);
    }
    return dialogAjaxDone(SystemConstant.DWZ_CODE_OK_MESSAGE, null, null, null, null);
  }

  @RequestMapping("validateResourceCode")
  @ResponseBody
  public boolean validateResourceCode(String resourceCode, Model model) {
    boolean isValid = true;
    if (!StringUtils.isBlank(resourceCode)) {
      ResourceEntity resourceEntity = adminResourceService.selectResource(resourceCode);
      if (resourceEntity != null) {
        isValid = false;
      }
    }
    return isValid;
  }

  @RequestMapping("deleteResource")
  @ResponseBody
  public DWZResult deleteResource(Model model, String navTabId, String id, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isEmpty(ids)) {
      return ajaxError(SystemConstant.PARAMETERNULL);
    }
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = adminResourceService.deleteResource(res);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      return navTabAjaxDone(navTabId, null, null, null,
          SystemConstant.DWZ_CODE_OK_MESSAGE,null);
    } else {
      HashMap<String, Object> map = new HashMap<String, Object>();
      map.put("title", "详细报告");
      map.put("data", reports);
      String jsonData = JSON.toJSONString(map);
      String forwardUrl = request.getContextPath() + "/manage/common/showReport";
      return getDWZJsonObject(DwzStatusCode.OK, null, null, null, DwzCallbackType.EMPTY, forwardUrl, null, jsonData);
    }
  }

  @RequestMapping("getResourceType")
  @ResponseBody
  public String getResourceType(Model model, String navTabId, HttpServletRequest request) {
    List<ECode> types = admineCodeService.selectECodeList(RESOURCETYPEECODE, SystemConstant.LANGUAGE_CODE_ZH);
    StringBuilder sbTypes = new StringBuilder();
    if (types != null) {
      for (ECode type : types) {
        sbTypes.append(",[");
        sbTypes.append("\"" + type.geteCode() + "\",");
        sbTypes.append("\"" + type.geteCodeText() + "\"");
        sbTypes.append("]");
      }
    }
    return sbTypes.toString();
  }

}
